﻿using Microsoft.AspNetCore.Mvc;
using IdentityService.Models;
using System.Threading.Tasks;

namespace IdentityService.Controllers
{
    [ApiController]
    [Route("/api/identity/users")]
    public class UserController : Controller
    {
        private readonly ILogger<UserController> _logger;

        private static List<User> Users = new List<User>()
        {
            new User(){ Id = 1, Name = "Jack"},
            new User(){ Id = 2, Name = "Tom"},
            new User(){ Id = 3, Name = "Franck"},
            new User(){ Id = 4, Name = "Tony"},
        };

        public UserController(ILogger<UserController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public async Task<List<User>>  GetAllAsync()
        {
            return await Task.Run(() => 
            { 
                return Users; 
            });
        }


        [HttpGet]
        [Route("{id}")]
        public async Task<User> GetAsync(int id)
        {
            return await Task.Run(() =>
            {
                var entity = Users.FirstOrDefault(p => p.Id == id);
                if (entity == null)
                {
                    throw new Exception($"未找到用户:{id}");
                }
                return entity;
            });
        }

        [HttpPost]
        public async Task<User> CreateAsync(User user)
        {
            return await Task.Run(() =>
            {
                Users.Add(user);
                return user;
            });
        }

        [HttpPut]
        [Route("{id}")]
        public async Task<User> UpdateAsync(int id, User user)
        {
            return await Task.Run(() =>
            {
                var entity = Users.FirstOrDefault(p => p.Id == id);
                if(entity == null)
                {
                    throw new Exception($"未找到用户:{id}");
                }
                entity.Name = user.Name;
                return entity;
            });
        }

        [HttpDelete]
        [Route("{id}")]
        public async Task<User> DeleteAsync(int id)
        {
            return await Task.Run(() =>
            {
                var entity = Users.FirstOrDefault(p => p.Id == id);
                if (entity == null)
                {
                    throw new Exception($"未找到用户:{id}");
                }
                Users.Remove(entity);

                return entity;
            });
        }
    }

    
}
